from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
import time
import logging
import json

from app.core.config import settings
from app.api.v1.api import api_router

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="HackPlay竞赛开黑平台API",
    openapi_url="/api/v1/openapi.json",
    docs_url="/api/v1/docs",
    redoc_url="/api/v1/redoc",
)

# CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=json.loads(settings.CORS_ORIGINS),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 信任主机中间件
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"]  # 生产环境中应该限制具体域名
)


# 请求处理时间中间件
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"Global exception: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error"}
    )


# 健康检查
@app.get("/health")
async def health_check():
    return {"status": "healthy", "version": settings.APP_VERSION}


# 根路径
@app.get("/")
async def root():
    return {
        "message": "Welcome to HackPlay API",
        "version": settings.APP_VERSION,
        "docs": "/api/v1/docs",
        "redoc": "/api/v1/redoc"
    }


# 便捷的文档访问路由
@app.get("/docs")
async def docs_redirect():
    """重定向到API文档"""
    return RedirectResponse(url="/api/v1/docs")


@app.get("/redoc")
async def redoc_redirect():
    """重定向到ReDoc文档"""
    return RedirectResponse(url="/api/v1/redoc")


# 包含API路由
app.include_router(api_router, prefix="/api/v1")


# 启动事件
@app.on_event("startup")
async def startup_event():
    logger.info("HackPlay API is starting up...")


# 关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    logger.info("HackPlay API is shutting down...")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG
    )